package com.katze.boot.plugins.security.filter;

import com.katze.common.ResponseStatus;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.lang.management.ManagementFactory;

public class SpringDocFilter extends OncePerRequestFilter implements IPathMatcher {
    private static final Logger log = LoggerFactory.getLogger(SpringDocFilter.class);

    private final OrRequestMatcher orRequestMatcher;
    private final String pid;
    private final String[] patterns = new String[]{"/v3/api-docs/**", "/swagger-api/docs/**", "/swagger-ui/**"};

    public SpringDocFilter() {
        this.pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        this.orRequestMatcher = new OrRequestMatcher(matchers());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (orRequestMatcher.matches(request)) {
            // 在这里添加自定义逻辑
            if (log.isDebugEnabled()) {
                log.info("SpringDoc URL filter executed for {}", request.getRequestURI());
            }
            // 请求来源地址
            String referer = request.getHeader("referer");
            if ((referer != null && referer.endsWith("?token="+pid)) || pid.equals(request.getParameter("token"))) {
                chain.doFilter(request, response);
            } else {
                response.setStatus(ResponseStatus.FORBIDDEN.value());
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"code\":" + ResponseStatus.FORBIDDEN.value() + ",\"type\":\"error\",\"message\":\"禁止未授权访问\"}");
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public String[] getPatterns() {
        return patterns;
    }
}
